<template>
  <!-- 校区续费统计模块 -->
  <el-row :gutter="16" class="data-row">
    <el-col :span="24">
      <el-card class="data-card" shadow="never">
        <div slot="header" class="card-header">
          <div class="header-left">
            <i class="el-icon-s-finance" />
            <span>校区续费统计</span>
          </div>
          <div class="header-right">
            <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" size="small" style="width: 240px; margin-right: 8px;" @change="handleFilterChange" />
            <el-select v-model="filterForm.brand" placeholder="选择品牌" size="small" style="width: 120px; margin-right: 8px;" @change="handleFilterChange">
              <el-option label="全部品牌" value="" />
              <el-option v-for="item in brandOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
            </el-select>
            <el-select v-model="filterForm.campusType" placeholder="选择校区类型" size="small" style="width: 120px; margin-right: 8px;" @change="handleFilterChange">
              <el-option label="全部类型" value="" />
              <el-option v-for="item in campusTypeOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
            </el-select>

            <el-button size="small" icon="el-icon-refresh" :loading="loading" @click="refreshData">刷新</el-button>
          </div>
        </div>
        <div v-loading="loading">
          <el-table :data="pivotData" size="small" stripe border show-summary :summary-method="getPivotSummaries" sum-text="总计" class="report-table">
            <el-table-column prop="month" label="月份" min-width="120" align="center" >
              <template slot-scope="scope">
                <span class="data-primary">{{ scope.row.month }}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="area in areas" :key="area.code" :label="area.name" align="center">
              <el-table-column :prop="'area_' + area.code + '_shouldRenew'" label="应续费" min-width="80" align="center">
                <template slot-scope="scope">
                  <span class="data-info">{{ scope.row['area_' + area.code + '_shouldRenew'] || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column :prop="'area_' + area.code + '_renewed'" label="已续费" min-width="80" align="center">
                <template slot-scope="scope">
                  <span class="data-success">{{ scope.row['area_' + area.code + '_renewed'] || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column :prop="'area_' + area.code + '_notRenewed'" label="未续费" min-width="80" align="center">
                <template slot-scope="scope">
                  <span class="data-danger">{{ scope.row['area_' + area.code + '_notRenewed'] || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column :prop="'area_' + area.code + '_renewalRate'" label="续费率" min-width="90" align="center">
                <template slot-scope="scope">
                  <span :class="getRenewalRateClass(scope.row['area_' + area.code + '_renewalRate'])">{{ (scope.row['area_' + area.code + '_renewalRate'] || 0).toFixed(2) }}%</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="总计" align="center">
              <el-table-column prop="totalShouldRenew" label="应续费" min-width="80" align="center">
                <template slot-scope="scope">
                  <span class="data-info">{{ scope.row.totalShouldRenew || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="totalRenewed" label="已续费" min-width="80" align="center">
                <template slot-scope="scope">
                  <span class="data-success">{{ scope.row.totalRenewed || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="totalNotRenewed" label="未续费" min-width="80" align="center">
                <template slot-scope="scope">
                  <span class="data-danger">{{ scope.row.totalNotRenewed || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="totalRenewalRate" label="续费率" min-width="90" align="center">
                <template slot-scope="scope">
                  <span :class="getRenewalRateClass(scope.row.totalRenewalRate)">{{ (scope.row.totalRenewalRate || 0).toFixed(2) }}%</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
import { getCampusRenewalStatistics } from '@/api/report/branch'

export default {
  name: 'RenewalStatisticsReport',
  props: {
    // 品牌选项
    brandOptions: {
      type: Array,
      default: () => []
    },
    // 管理区域选项
    managementAreaOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 获取当前年度时间范围
    const getCurrentYearRange = () => {
      const currentYear = new Date().getFullYear()
      const startDate = `${currentYear}-01-01`
      const endDate = `${currentYear}-12-31`
      return [startDate, endDate]
    }

    return {
      loading: false,
      pivotData: [],
      areas: [],
      campusTypeOptions: [], // 校区类型选项
      filterForm: {
        dateRange: getCurrentYearRange(),
        brand: 'bell', // 默认贝尔安亲
        campusType: 'franchisee' // 默认加盟校
      }
    }
  },
  watch: {
    // 移除managementAreaOptions监听，因为已不再使用管理区域筛选
  },
  mounted() {
    this.loadCampusTypeOptions()
    this.loadRenewalData()
  },
  methods: {
    // 加载校区类型选项
    async loadCampusTypeOptions() {
      try {
        const response = await this.$store.dispatch('base/getDictionaryData', { sort: 'CampusType' })
        this.campusTypeOptions = response || []
      } catch (error) {
        console.error('加载校区类型选项失败:', error)
        this.campusTypeOptions = []
      }
    },

    // 加载续费统计数据
    async loadRenewalData() {
      this.loading = true

      try {
        // 安全获取时间参数，确保有默认值
        const startDate = this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : this.getCurrentYearRange()[0]
        const endDate = this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : this.getCurrentYearRange()[1]

        // 构建查询参数 - 确保startDate和endDate是必需的
        const params = {
          startDate: startDate,
          endDate: endDate
        }

        // 添加筛选参数（使用默认值）
        if (this.filterForm.brand) {
          params.brand = this.filterForm.brand
        }

        if (this.filterForm.campusType) {
          params.campusType = this.filterForm.campusType
        }

        // 调用续费统计接口
        const renewalResponse = await getCampusRenewalStatistics(params)
        const responseData = renewalResponse.data || renewalResponse

        // 使用后端返回的管理区域列表并排序 - 强制类型转换
        if (responseData.managementAreas) {
          this.areas = responseData.managementAreas.map(area => {
            return {
              ...area,
              sortCode: this.getRegionSort(area.code)
            }
          })
        }

        // 直接使用后端返回的透视表数据
        if (responseData.pivotData) {
          this.pivotData = responseData.pivotData.map(item => {
            const mappedItem = {
              month: item.month,
              totalShouldRenew: Number(item.totalShouldRenewCount || 0),
              totalRenewed: Number(item.totalRenewedCount || 0),
              totalNotRenewed: Number(item.totalNotRenewedCount || 0),
              totalRenewalRate: Number(item.totalRenewalRate || 0),
              ...this.processRenewalAreaData(item.areaData || {})
            }

            // 数据一致性验证
            const calculatedNotRenewed = mappedItem.totalShouldRenew - mappedItem.totalRenewed
            const calculatedRate = mappedItem.totalShouldRenew > 0 ? ((mappedItem.totalRenewed / mappedItem.totalShouldRenew) * 100).toFixed(2) : 0

            if (Math.abs(calculatedNotRenewed - mappedItem.totalNotRenewed) > 0.01) {
              console.warn(`续费数据不一致警告 - ${item.month}: 计算未续费=${calculatedNotRenewed}, 返回未续费=${mappedItem.totalNotRenewed}`)
            }

            if (Math.abs(Number(calculatedRate) - mappedItem.totalRenewalRate) > 0.01) {
              console.warn(`续费率不一致警告 - ${item.month}: 计算续费率=${calculatedRate}%, 返回续费率=${mappedItem.totalRenewalRate}%`)
            }
            return mappedItem
          })
        } else {
          this.pivotData = []
        }

        // 计算续费指标并通知父组件数据已更新
        this.calculateRenewalMetrics()

        this.$emit('data-updated', {
          pivotData: this.pivotData,
          areas: this.areas
        })
      } catch (error) {
        this.$message.error('续费统计数据加载失败')
        console.error('续费统计数据加载错误:', error)

        // 如果API调用失败，初始化空数据
        this.pivotData = []
        this.areas = []
      } finally {
        this.loading = false
      }
    },

    // 处理续费区域数据
    processRenewalAreaData(areaData) {
      const result = {}
      Object.keys(areaData).forEach(areaKey => {
        const data = areaData[areaKey]
        result[`area_${areaKey}_shouldRenew`] = Number(data.shouldRenewCount || 0)
        result[`area_${areaKey}_renewed`] = Number(data.renewedCount || 0)
        result[`area_${areaKey}_notRenewed`] = Number(data.notRenewedCount || 0)
        result[`area_${areaKey}_renewalRate`] = Number(data.renewalRate || 0)
      })
      return result
    },

    // 获取当前年度时间范围
    getCurrentYearRange() {
      const currentYear = new Date().getFullYear()
      const startDate = `${currentYear}-01-01`
      const endDate = `${currentYear}-12-31`
      return [startDate, endDate]
    },

    // 获取续费率标签类型
    getRenewalRateTagType(rate) {
      const numRate = Number(rate || 0)
      if (numRate >= 80) {
        return 'success' // 绿色：续费率>=80%
      } else if (numRate >= 60) {
        return 'warning' // 橙色：续费率60%-79%
      } else {
        return 'danger' // 红色：续费率<60%
      }
    },

    // 获取续费率样式类
    getRenewalRateClass(rate) {
      const numRate = Number(rate || 0)
      if (numRate >= 80) {
        return 'data-success' // 绿色：续费率>=80%
      } else if (numRate >= 60) {
        return 'data-warning' // 橙色：续费率60%-79%
      } else {
        return 'data-danger' // 红色：续费率<60%
      }
    },

    // 获取透视表汇总
    getPivotSummaries(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }

        const values = data.map(item => Number(item[column.property])).filter(value => !isNaN(value))

        if (column.property.includes('Rate')) {
          // 对于续费率列，计算加权平均值
          let shouldRenewProp, renewedProp

          if (column.property === 'totalRenewalRate') {
            // 总计列的续费率计算
            shouldRenewProp = 'totalShouldRenew'
            renewedProp = 'totalRenewed'
          } else {
            // 区域列的续费率计算
            shouldRenewProp = column.property.replace('renewalRate', 'shouldRenew')
            renewedProp = column.property.replace('renewalRate', 'renewed')
          }

          const totalShouldRenew = data.reduce((sum, item) => {
            return sum + Number(item[shouldRenewProp] || 0)
          }, 0)
          const totalRenewed = data.reduce((sum, item) => {
            return sum + Number(item[renewedProp] || 0)
          }, 0)

          sums[index] = totalShouldRenew > 0 ? ((totalRenewed / totalShouldRenew) * 100).toFixed(2) + '%' : '0.00%'
        } else {
          sums[index] = values.length > 0 ? values.reduce((prev, curr) => prev + curr, 0) : 0
        }
      })

      return sums
    },

    // 计算续费指标
    calculateRenewalMetrics() {
      // 计算续费率（使用模拟数据，与原逻辑保持一致）
      const renewalRate = 78 + Math.floor(Math.random() * 15) // 模拟数据：78%-93%之间

      // 模拟增长率（-7% 到 +7%）
      const renewalGrowthRate = Math.floor(Math.random() * 15) - 7

      // 通过事件发送指标数据给父组件
      this.$emit('metrics-updated', {
        renewalRate,
        renewalGrowthRate
      })
    },

    // 处理筛选条件变化
    handleFilterChange() {
      this.loadRenewalData()
      this.$emit('filter-change', this.filterForm)
    },

    // 获取区域排序值
    getRegionSort(regionCode) {
      const region = this.managementAreaOptions.find(item => item.enCode === regionCode)
      const sortCode = region ? region.sortCode || 999 : 999
      // 强制转换为数字类型
      const numericSortCode = Number(sortCode)
      return isNaN(numericSortCode) ? 999 : numericSortCode
    },

    // 刷新数据
    refreshData() {
      this.loadRenewalData()
      this.$emit('refresh')
    }
  }
}
</script>

<style scoped>
@import './shared-table-styles.scss';
</style>
